import numpy as np
import cv2 as cv 
import sys
#创建VideoCapture对象，制定的设备索引号为index = 0
cap = cv.VideoCapture(1)
if not cap.isOpened():
    print ("failed to show")
    exit()
fps = cap.get(cv.CAP_PROP_FPS)
frame_index = 0     # Use for the time when you need to save the pic and make them in lines
#可用鼠标调节大小的window
cv.namedWindow('Camera playing',cv.WINDOW_NORMAL | cv.WINDOW_KEEPRATIO)
#读取视频until按下ESC
while cap.isOpened():
    #调用VideoCapture对象的read（）方法捕捉视频的图像帧
    ret,frame = cap.read()
    frame_index=frame_index+1
    #if 正常的读取帧，反悔哦只ret为Ture否则为False退出程序
    if not ret :
        print("Cant receive frame (stream end ?).Exiting...")
        break
#下面代码将对图像帧进项简单的处理
    img = np.flip(frame,1)#水平翻转图像帧
    img_montage = np.hstack((frame,img))#将两张图像拼接为一张图像
    cv.imshow('Camera Playiing ',img_montage)
    #按ESC键退出。按S键将图像帧保存为文件 （当前目录）
    keycode = cv.waitKey(int(1000/fps))&0xFF
    if keycode == 27:
        break 
    elif keycode == ord('s'):
        frame_name = "camera_name,frame_{}.jpg".format(frame_index)
        cv.imwrite(frame_name,frame)# 保持图形
        cap.release()#释放摄像头资源
        cv.destroyAllWindows()#关闭图像显示窗口并释放资源